
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 * Servlet implementation class addRoomService
 */
@WebServlet("/addRoomService")
public class editRoomService extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public editRoomService() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		response.setContentType("text/html");
		int maxMemSize = 4 * 1024;
		int maxFileSize = 50 * 1024;
		File destinationDir;
		File file;
		String realPath = getServletContext().getRealPath("");
		String filePath;
		HttpSession hostSession = request.getSession(true);
		String hostFamilyID = hostSession.getAttribute("hostFamilyID").toString();
		int roomID = Integer.parseInt(hostSession.getAttribute("roomID").toString());
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();;
		try{
	        session.beginTransaction();
			} catch(Exception ex){
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
			}
		room roomObj = (room)session.load(room.class,roomID);
		roomObj.setHasInsideBathroom('N');
		roomObj.setHasInsideTV('N');
		roomObj.setHasInsideAirCondition('N');
		roomObj.setHasInsideFridge('N');
		List<String> imagePath = new ArrayList<String>();
		String roomName ="";
		java.io.PrintWriter out = response.getWriter();
		if (!isMultipart) {
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Servlet upload</title>");
			out.println("</head>");
			out.println("<body>");
			out.println("<p>No file uploaded</p>");
			out.println("</body>");
			out.println("</html>");
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File(realPath + "/temp/"));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);

		try {
			// Parse the request to get file items.
			List fileItems = upload.parseRequest(request);
			// Process the uploaded file items
			Iterator i = fileItems.iterator();
			roomObj.setHostFamilyID(Integer.parseInt(hostFamilyID));
			int countFormField = 1;
			int countNotFomrField = 1;
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Servlet upload</title>");
			out.println("</head>");
			out.println("<body>");
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (fi.isFormField()) {
					if(countFormField<5)
					{
						if(countFormField==1){roomName = fi.getString();roomObj.setRoomName(roomName);}
						if(countFormField==2){roomObj.setRoomType(fi.getString());}
						if(countFormField==3){roomObj.setRoomSize(Integer.parseInt(fi.getString()));}
						if(countFormField==4){roomObj.setPricePerDay(Double.parseDouble(fi.getString()));}
						countFormField++;
					}
					else
					{
						if(fi.getFieldName().equals("facility1")){roomObj.setHasInsideBathroom(fi.getString().charAt(0));}
						if(fi.getFieldName().equals("facility2")){roomObj.setHasInsideTV(fi.getString().charAt(0));}
						if(fi.getFieldName().equals("facility3")){roomObj.setHasInsideAirCondition(fi.getString().charAt(0));}
						if(fi.getFieldName().equals("facility4")){roomObj.setHasInsideFridge(fi.getString().charAt(0));}
					}
				}
				else {					
		            // Get the uploaded file parameters					
					filePath = "/images/rooms/" + roomID + "/";
					destinationDir = new File(realPath + filePath);
					if (!destinationDir.exists())
						destinationDir.mkdir();
		            String fieldName = fi.getFieldName();
		            String fileName = fi.getName();
		            String contentType = fi.getContentType();
		            boolean isInMemory = fi.isInMemory();
		            long sizeInBytes = fi.getSize();
		            String saveRealPath = realPath + filePath + countNotFomrField + ".jpg";
		            String saveImagePath = filePath + countNotFomrField + ".jpg";
		            // Write the file
		            file = new File(saveRealPath) ;
		            if(fileName != "")
		            {
		            fi.write( file );
		            imagePath.add(saveImagePath);
		            out.println("Uploaded Filename: " + fileName + "<br>");
		            }
		            countNotFomrField++;
		         }				 
			}
			try{
				session.saveOrUpdate(roomObj);
				session.getTransaction().commit();
		        for(String s : imagePath){
		        int check = getPhotoID(s);
		        if(check==0)
		        {
		        	Session session1 = HibernateUtil.getSessionFactory().getCurrentSession();
		            session1.beginTransaction();
		        	roomPhoto roomPhotoObj = new roomPhoto();
		        	roomPhotoObj.setRoomID(roomID);
		        	roomPhotoObj.setPhotoURL(s);
		        	session1.saveOrUpdate(roomPhotoObj);
		        	session1.getTransaction().commit();
		        }	        
		        }	        
				} catch(Exception ex){
					HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
				}
			out.println("</body>");
			out.println("</html>");
		} catch (Exception ex) {
			System.out.println(ex);
		}
		
	}
	protected int getPhotoID(String photoURL)
	{
		int temp = 0;
		List<roomPhoto> roomPhotoList = new ArrayList<roomPhoto>();
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        String sqlString = "select * from roomphotos where photoURL = '" + photoURL + "'";
		Query queryResult = session.createSQLQuery(sqlString).addEntity(roomPhoto.class);;
		roomPhotoList = queryResult.list();
		if(roomPhotoList.isEmpty())
			temp = 0;
		else
			temp = roomPhotoList.get(0).getRoomPhotoID();
        session.getTransaction().commit();
        System.out.println("RoomPhotoID:" + temp);
		} catch(Exception ex){
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
		}
        return temp;
	}

}
